#!/bin/bash
# =================================================================
# LimeReader 已安装应用修复脚本
# 用途：修复因代码签名问题无法运行的已安装应用
# =================================================================

set -e

APP_PATH="/Applications/LimeReader.app"

echo ""
echo "=========================================="
echo " LimeReader 应用修复工具"
echo "=========================================="
echo ""

# 检查应用是否存在
if [ ! -d "$APP_PATH" ]; then
    echo "[ERROR] 未找到应用程序: $APP_PATH"
    echo "请先安装 LimeReader"
    exit 1
fi

echo "[INFO] 找到应用: $APP_PATH"
echo ""

# 检查是否有写权限
if [ ! -w "$APP_PATH" ]; then
    echo "[ERROR] 没有写权限，需要使用 sudo"
    echo "请运行: sudo bash $0"
    exit 1
fi

echo "[STEP 1] 移除隔离属性 (quarantine)..."
xattr -dr com.apple.quarantine "$APP_PATH" 2>/dev/null || true
echo "[SUCCESS] 隔离属性已移除"
echo ""

echo "[STEP 2] 执行 ad-hoc 代码签名..."
echo ""

# 1. 签名所有dylib和so文件
echo "[INFO] 签名动态库..."
find "$APP_PATH/Contents" -type f \( -name "*.dylib" -o -name "*.so" \) -print0 2>/dev/null | while IFS= read -r -d '' lib; do
    echo "  签名: $(basename "$lib")"
    codesign --force --sign - --timestamp=none "$lib" 2>/dev/null || true
done

# 2. 签名所有frameworks
if [ -d "$APP_PATH/Contents/Frameworks" ]; then
    echo ""
    echo "[INFO] 签名 Frameworks..."
    for fw in "$APP_PATH/Contents/Frameworks"/*.framework "$APP_PATH/Contents/Frameworks"/*.dylib; do
        if [ -e "$fw" ]; then
            echo "  签名: $(basename "$fw")"
            codesign --force --sign - --timestamp=none --deep "$fw" 2>/dev/null || true
        fi
    done
fi

# 3. 签名插件
if [ -d "$APP_PATH/Contents/PlugIns" ]; then
    echo ""
    echo "[INFO] 签名插件..."
    find "$APP_PATH/Contents/PlugIns" -type f -perm +111 -print0 2>/dev/null | while IFS= read -r -d '' plugin; do
        echo "  签名: $(basename "$plugin")"
        codesign --force --sign - --timestamp=none "$plugin" 2>/dev/null || true
    done
fi

# 4. 签名主执行文件
echo ""
echo "[INFO] 签名主执行文件..."
codesign --force --sign - --timestamp=none "$APP_PATH/Contents/MacOS/LimeReader" 2>/dev/null || true

# 5. 签名整个应用包（带 entitlements）
echo ""
echo "[INFO] 签名应用包..."

# 创建临时 entitlements 文件
TEMP_ENTITLEMENTS=$(mktemp /tmp/limereader_entitlements.XXXXXX)
cat > "$TEMP_ENTITLEMENTS" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
</dict>
</plist>
EOF

# 使用临时文件进行签名
codesign --force --sign - --timestamp=none --deep --entitlements "$TEMP_ENTITLEMENTS" "$APP_PATH" 2>&1 || true

# 清理临时文件
rm -f "$TEMP_ENTITLEMENTS"

echo ""
echo "[STEP 3] 验证签名..."
if codesign -v "$APP_PATH" 2>&1; then
    echo "[SUCCESS] ✅ 签名验证通过"
else
    echo "[WARNING] ⚠️  签名验证有警告，但应该可以运行"
fi

echo ""
echo "[STEP 4] 设置正确的权限..."
chmod -R u+w "$APP_PATH"
chmod +x "$APP_PATH/Contents/MacOS/LimeReader"
echo "[SUCCESS] 权限设置完成"

echo ""
echo "=========================================="
echo " 修复完成！"
echo "=========================================="
echo ""
echo "现在可以尝试运行："
echo "  open /Applications/LimeReader.app"
echo ""
echo "或通过终端运行："
echo "  /Applications/LimeReader.app/Contents/MacOS/LimeReader"
echo ""
echo "如果仍然无法运行，请查看详细日志："
echo "  log show --predicate 'subsystem == \"com.apple.security\"' --last 5m | grep -i limereader"
echo ""

